import { Component } from '@angular/core';
import { NzModalService, NzModalRef, NzNotificationService } from 'ng-zorro-antd';
import { ApiService } from '@srvs/api.service';

import { EditResourceComponent } from './edit-resource/edit-resource.component';

@Component({
  selector: 'resource-management',
  templateUrl: './resource-management.component.html'
})
export class ResourceManagementComponent {

  public config: any = {
    loading: false
  };
  public data: any = {
    resources: [],
    resourceTotal: 0
  };
  public params: any = {
    pageIndex: 1,
    pageSize: 10,
    lastModifiedTimeSort: null,
    keywords: null
  };
  private debounce: any;

  constructor(
    private modalSrv: NzModalService,
    private msgSrv: NzNotificationService,
    private apiSrv: ApiService
  ) {
    this.load();
  }

  /**
   * 加载资源列表
   * @param pageIndex 页数
   */
  public load(pageIndex?: number): void {
    if (typeof pageIndex === 'number') this.params.pageIndex = pageIndex + 1;

    let apiResources: string = '/api/uris';
    const params: any = {
      page: this.params.pageIndex - 1,
      size: this.params.pageSize,
      sort: this.params.lastModifiedTimeSort
        ? `lastModifiedTime,${this.params.lastModifiedTimeSort.slice(0, -3)}`
        : 'id,asc'
    },
      httpOptions: any = {
        observe: 'response'
      };

    if (this.params.keywords) {
      apiResources = '/api/_search/uris';
      params.query = `"${this.params.keywords}"`;
    }

    this.config.loading = true;
    this.apiSrv.get(apiResources, params, httpOptions).subscribe(
      res => {
        if (!Array.isArray(res.body)) return;
        if (
          res.body.length === 0 &&
          this.params.pageIndex > 1
        ) {
          this.load(this.params.pageIndex - 2);
        } else {
          this.data.resources = res.body;
          this.data.resourceTotal = res.headers.get('X-Total-Count');
        }
      },
      error => {
        this.msgSrv.error('资源列表加载失败！', error.message);
        this.config.loading = false;
      },
      () => this.config.loading = false
    );
  }

  /**
   * 创建资源
   */
  public createResource(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建资源',
      nzContent: EditResourceComponent,
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditResourceComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            this.load();
            this.msgSrv.success('创建资源成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建资源失败！', error.message);
            ref.getInstance().nzOkLoading = false
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 修改资源
   * @param resource 资源数据
   */
  public updateCompany(resource: any): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '修改资源',
      nzContent: EditResourceComponent,
      nzComponentParams: { data: resource },
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditResourceComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const index: number = this.data.resources.indexOf(resource),
              resources: any[] = [...this.data.resources];
            resources[index] = data;
            this.data.resources = resources;
            this.msgSrv.success('修改资源成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('修改资源失败！', error.message);
            ref.getInstance().nzOkLoading = false
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 删除资源
   * @param resource 资源数据
   */
  public deleteResource(resource: any): void {
    const apiResources: string = `/api/uris/${resource.id}`;
    this.apiSrv.delete(apiResources).subscribe(
      () => {
        this.load();
        this.msgSrv.success('删除资源成功！', null);
      },
      error => this.msgSrv.error('删除资源失败！', error.message)
    );
  }

  /**
   * 防抖动加载资源数据
   */
  public debounceLoad(): void {
    clearTimeout(this.debounce);
    this.debounce = setTimeout(() => this.load(0), 500);
  }

}
